import Vue from 'vue'
const myws = new Vue({
  data() {
    return {
      ws: '',
      userInfo: '',
      timer:null,
      state: 0,
      timeout:null
    }
  },
  methods: {
    init(userInfo) {
      console.log('wsuserInfo:', userInfo)
      this.userInfo = userInfo;
      // this.ws = new WebSocket("ws://report.wsloan.com:8888/css/websocket");
      // this.ws = new WebSocket("ws://192.168.0.135:8080/css/websocket");
      const wsUrl = window.path.slice(window.path.indexOf(':'))
      console.log('wsUrl:',wsUrl)
      this.ws = new WebSocket(`ws${wsUrl}websocket`)
      this.ws.onopen = this.WSonOpen;
      this.ws.onmessage = this.WSonMessage;
      this.ws.onclose = this.WSonClose;
      this.ws.onerror = this.WSonError;
    },
    WSonOpen() {
      // console.log('myws open')
      this.state = 1
      this.ws.send(`sessionId${this.userInfo.sessionId}`)
      const timer = setTimeout(()=>{
        clearTimeout(timer)
        this.keepAlive() 
      },2 * 1000)
      // this.lx();
    },
    WSonMessage (evt) {
      this.$notify({
        title: '提示',
        message: evt.data,
        duration: 0
      });
    },
    WSonClose() {
      this.state = 0
    },
    WSonError() {
    },
    lx () {
      // 离线超过30分钟，给组长发送信息提示
      if (this.userInfo.power == 3) {
        this.timeout = setTimeout(() => {
          this.circle()
        },30 * 60 * 1000)
      }
    },
    circle(){
      // 离线时间考虑午休时间，如果是午休则不进行离线提醒
      const nowDate = new Date()
      const time = nowDate.getHours() + Number.parseFloat((nowDate.getMinutes() / 60).toFixed(2))
      clearTimeout(this.timeout)
      if (time >= 11.5 && time < 13) {
        this.timeout = setTimeout(() => {
          this.circle()
        },30 * 60 * 1000)
      } else {
        this.ws.send(`${this.userInfo.userName},${this.userInfo.userGroupId}`)
      }
    },
    keepAlive(){
      this.timer = setInterval(()=>{
        //this.ws.send(`${this.userInfo.userName},${this.userInfo.userGroupId}`);
        this.ws.send('keepalive')
      },45 * 1000)
    },
    cleartimeout () {
      clearTimeout(this.timeout);
    },
  }
})
window.myws = myws
export default myws
